package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String website;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //检查参数:登录，检查分页
        dto.checkParam();
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //封装查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //按照文章标题模糊查询
        queryWrapper.like(StringUtils.isNoneBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //Pindao
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //根据文章状态查询
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //按照时间区间查询
        // 2.4 大于等于开始时间
        queryWrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 2.5 结束时间
        queryWrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());

        //查询当前用户登录id
        queryWrapper.eq(WmNews::getUserId, user.getId());
        //按照创建的时间降序
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        //分页查询
        IPage<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //执行查询，封装返回结果
        IPage<WmNews> pageResult = page(pageReq, queryWrapper);
        //  page(dto.getSize(),dto.getPage(),pageReq.getTotal())
        //将图片前缀访问路径设置到host属性
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        //处理文章图片
        responseResult.setHost(website);


        return responseResult;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1.检查参数，内容状态是否登录
        if (StringUtils.isBlank(wmNewsDto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }

        Short status = wmNewsDto.getStatus();//0是草稿，1是待审核
        if (status == null || (status.intValue() != 0 && status.intValue() != 1)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章状态错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        //1.1检查参数，内容状态是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.2基于dto创建wm_news
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);//拷贝属性
        //1.3如果type等于-1.将type设置为null，避免保存出错
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //1.4如果传入的images集合不为空，转为字符串，用逗号拼接
        if (CollectionUtils.isNotEmpty(wmNewsDto.getImages())) {
            String imageStr = imageListToStr(wmNewsDto.getImages());
            wmNews.setImages(imageStr);

        }
        wmNews.setUserId(user.getId());
        //2.保存或修改wmNews
        saveOrUpdateWmNews(wmNews);
        //3.如果是审核状态，需要保存内容图片和封面图片与素材的关联关系
        if (status.intValue() == 0) {//caogao
            return ResponseResult.okResult();
        }
        // 3.1 抽取出内容中所涉及的所有图片
        List<String> contentImages = parseContentImages(wmNewsDto.getContent());//得到内容图片集合
        //3.2保存素材关联关系
        if (CollectionUtils.isNotEmpty(contentImages)) {
            saveRelativeInfo(contentImages, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // // 3.3    保存封面图片与素材的关联关系
        saveRelativeInfoForCover(contentImages, wmNews, wmNewsDto);
        // 3.4    如果封面 type为-1 需要基于内容图片生成封面图片
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(website);
        return result;
    }

    /**
     * 根据文章id删除
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
//        //1.检查参数
//        if(dto == null || dto.getId() == null){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
//
//        //2.查询文章
//        WmNews wmNews = getById(dto.getId());
//        if(wmNews == null){
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
//        }
//
//        //3.判断文章是否发布
//        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
//        }
//
//        //4.修改文章状态，同步到app端（后期做）TODO
//        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
//            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
//                    .set(WmNews::getEnable,dto.getEnable()));
//        }
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
// 1. 检查参数  (  id   enable (0   1)  )
        if (dto.getId() == null || dto.getEnable() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable.intValue() != 0 && enable.intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        // 2. 根据id查询文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 检查文章状态是否为9 已发布
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章不是发布状态，无法上下架");
        }
        // 4. 修改 wmNews   enable
        wmNews.setEnable(enable);
        updateById(wmNews);
        return ResponseResult.okResult();
    }

    /**
     * 保存  封面 和 素材的关联关系
     *
     * @param contentImages
     * @param wmNews
     */
    private void saveRelativeInfoForCover(List<String> contentImages, WmNews wmNews, WmNewsDto wmNewsDto) {
        List<String> images = wmNewsDto.getImages();//封面图片列表
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //封面自动生成
            //如果url为空，设置无图模式
            if (CollectionUtils.isEmpty(contentImages)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            }else if (contentImages.size()<=2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        if (CollectionUtils.isNotEmpty(images)) { // 保存封面和素材的关联关系
            images = images.stream().map(url -> url.replaceAll(website, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * @param materialUrls 相关素材 url集合
     * @param newsId       文章id
     * @param type         0 内容中引用的素材   1 封面引用的素材
     *                     <p>
     *                     素材1.jpg      素材2.jpg    素材3.jpg
     */
    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        // 1. 查询 素材url集合  所对应的所有素材信息
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materialUrls)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用的素材不存在");
        }
        // 2. 将素材信息集合 转为 map集合   key:  url      value: id
        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        // 3. 遍历素材url集合，将每个url所对应的id 存入到素材id集合中
        List<Integer> materialIds = new ArrayList<>();
        materialUrls.forEach(url -> {
            if (!urlAndIdMap.containsKey(url)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用素材不存在");
            }
            materialIds.add(urlAndIdMap.get(url));

        });
        // 4. 调用mapper 批量插入方法   id集合  newsid   type保存
        wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);

    }

    /**
     * 抽取 文章内容中 所包含的所有图片  去除图片前缀
     * Map<String,String></>
     * map1:{type,text},{value,wenben}
     * map2:{type,image},{value,url}
     *
     * @param content "[ {type:text,value:文本内容},{type:image,value:图片url},{},{} ]"
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        List<String> imageList = contentMap.stream()
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))//取出key对应的value为image
                .map(map -> (String) map.get("value"))//取出map中的value，即url
                .map(url -> url.replaceAll(website, ""))
                .collect(Collectors.toList());
        return imageList;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全信息
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//上架
        //2.如果id为空，保存
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            //3.id不为空
            //3.1删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //3.2修改文章
            updateById(wmNews);
        }

    }

    /**
     * 将入参中封面集合，转为图片路径url字符串，前缀website替换为空，使用逗号拼接
     *
     * @param wmNewsDto
     * @return
     */
    private String imageListToStr(List<String> images) {
        return images.stream()
                .map(str -> str.replaceAll(website, ""))
                .collect(Collectors.joining(","));
    }
}
